package com.juxing.controller.client;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juxing.myenum.UserEnum;
import com.juxing.pojo.Product;
import com.juxing.pojo.User;
import com.juxing.service.ProductService;
import com.juxing.service.UserService;
import com.juxing.utils.JsonUtils;
import com.juxing.utils.ResResult;
import com.juxing.utils.UserRedisUtil;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@RestController
@RequestMapping("/client/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private UserRedisUtil userRedisUtil;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private ProductService productService;

	@Value("${wx.appId}")
	private String appId;
	@Value("${wx.secret}")
	private String secret;

	/**
	 * 微信注册
	 */
	@RequestMapping("/reg")
	public ResResult reg(String code, User user) throws Exception {
		// 获取openid
		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
				+ "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code", String.class);
		ObjectMapper mapper = new ObjectMapper();
		// json字符串转为Map对象
		Map map = mapper.readValue(result, Map.class);
		// {"session_key":"MB\/2x2X7ljCE2DqcKSBrqw==","expires_in":7200,"openid":"oIYEY0X0BZp040Y4gzoR4-JkrNGk"}
		if (map.get("errcode") != null) {
			return ResResult.build(UserEnum.LOGIN_ERROR.getCode(), UserEnum.LOGIN_ERROR.getMessage());
		}
		// 判断数据库中是否存在
		User dbuser = userService.byOpenId((String) map.get("openid"));
		if (dbuser != null) {
			return ResResult.build(UserEnum.USER_REG.getCode(), UserEnum.USER_REG.getMessage());
		}

		// 没有则保存
		User user2 = new User();
		user2.setOpenId((String) map.get("openid"));
		user2.setName(user.getName());
		user2.setPhone(user.getPhone());
		user2.setDormNumber(user.getDormNumber());
		user2.setHeadimg(user.getHeadimg());
		// 是否是推广过来的
		user2.setSuperior(user.getSuperior());
		user2.setExtendNumber(0);
		// 普通用户
		user2.setStatus(UserEnum.Leve1.getCode());
		userService.insertUser(user2);
		// 有返回
		return ResResult.ok();
	}

	/**
	 * 微信登录
	 */
	@RequestMapping("/login")
	public ResResult login(String code) throws Exception {
		// 获取openid
		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
				+ "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code", String.class);
		ObjectMapper mapper = new ObjectMapper();
		// json字符串转为Map对象
		Map map = mapper.readValue(result, Map.class);
		// {"session_key":"MB\/2x2X7ljCE2DqcKSBrqw==","expires_in":7200,"openid":"oIYEY0X0BZp040Y4gzoR4-JkrNGk"}
		if (map.get("errcode") != null) {
			return ResResult.build(UserEnum.LOGIN_ERROR.getCode(), UserEnum.LOGIN_ERROR.getMessage());
		}
		// 判断数据库中是否存在
		User dbuser = userService.byOpenId((String) map.get("openid"));
		if (dbuser == null) {
			return ResResult.build(UserEnum.NOT_REG.getCode(), UserEnum.NOT_REG.getMessage());
		}
		if(dbuser.getStatus()==UserEnum.Leve.getCode()) {
			return ResResult.build(UserEnum.OP_REEOR.getCode(), UserEnum.OP_REEOR.getMessage());
		}
		dbuser.setPassword(null);
		String token = UUID.randomUUID().toString();
		// 保存到redis
		redisTemplate.opsForValue().set("user:" + token, JsonUtils.objectToJson(dbuser), 86400, TimeUnit.SECONDS); // 保存1天
		// 有返回
		return ResResult.ok("user:" + token);
	}

	/**
	 * 根据token更新用户信息
	 * 
	 * @param token
	 * @param user
	 * @return
	 */
	@RequestMapping("/updateUser")
	public ResResult updateUser(String token, User user) {
		// 获取登录用户
		User loginUser = userRedisUtil.getUser(token);
		User dbuser = userService.byUserId(loginUser.getUserId());
		// 设置可以修改的值
		dbuser.setUserId(loginUser.getUserId());
		dbuser.setName(user.getName());
		dbuser.setPhone(user.getPhone());
		dbuser.setDormNumber(user.getDormNumber());
		// 更新
		userService.updateUser(dbuser);
		// 保存到redis
		redisTemplate.opsForValue().set(token, JsonUtils.objectToJson(dbuser), 86400, TimeUnit.SECONDS); // 保存1天
		return ResResult.ok();
	}

	/**
	 * 根据token获取用户信息
	 * 
	 * @param token
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
	public ResResult getUserInfo(String token) {
		// 获取登录用户
		User loginUser = userRedisUtil.getUser(token);
		User dbuser = userService.byUserId(loginUser.getUserId());
		return ResResult.ok(dbuser);
	}

	/**
	 * 登录是否过期
	 * 
	 * @param token
	 * @return
	 */
	@GetMapping("/userIsExpire")
	public ResResult userIsExpire(String token) {
		String userString = redisTemplate.opsForValue().get(token);
		if (userString == null) {
			return new ResResult(UserEnum.USER_EXPIRE.getCode(), UserEnum.USER_EXPIRE.getMessage(), null);
		}
		return ResResult.ok();
	}

	/**
	 * 根据用户id获取用户下的商品
	 * @param token
	 * @param pageNum
	 * @param pageSize
	 * @param status
	 * @return
	 */
	@GetMapping("/userProduct")
	public ResResult userProduct(String token, @RequestParam(defaultValue = "1") Integer pageNum,
			@RequestParam(defaultValue = "10") Integer pageSize, Integer status) {
		// 获取登录用户
		User loginUser = userRedisUtil.getUser(token);
		
		Example example = new Example(Product.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", loginUser.getUserId());
		criteria.andEqualTo("status", status);

		return ResResult.ok(productService.list(pageNum, pageSize, example));
	}

}
